package drrr.controller;

import drrr.orm.UserEntity;
import org.apache.struts2.ServletActionContext;

import java.util.regex.Pattern;

/**
 * 注册一个普通用户
 * Created by Xun on 2015/4/28.
 */
public class Register extends BaseAction {
    private String username;
    private String password;
    private String email;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String execute() throws Exception {
        UserEntity userEntity = new UserEntity();
        userEntity.setEmail(getEmail());
        userEntity.setPassword(getPassword());
        userEntity.setUsername(getUsername());
        getAllService().getUserService().insert(userEntity);
        ServletActionContext.getContext().getSession().put("user", userEntity);
        return super.execute();
    }

    @Override
    public void validate() {
        Pattern pattern = Pattern.compile("[a-zA-Z]/w{4,15}");
        if (pattern.matcher(this.getUsername()).matches()) {
            this.addFieldError("username", "用户名由字符字母开头，由字符或字母组成，且长度为5-16之间");

        } else if (this.getPassword().equals("")) {
            this.addFieldError("password", "密码不能为空");

        }
    }
}
